package com.zhou.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhou.dao.CheckGroupMapper;
import com.zhou.entity.PageResult;
import com.zhou.pojo.CheckGroup;
import com.zhou.pojo.CheckItem;
import com.zhou.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupMapper checkGroupMapper;


    @Override
    public void add(Integer[] checkItemIds, CheckGroup checkGroup) {
        checkGroupMapper.insert(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(), checkItemIds);
    }

    public void setCheckGroupAndCheckItem(Integer checkGroupId, Integer[] checkItemIds) {
        if (checkItemIds != null && checkItemIds.length > 0) {
            for (Integer checkItemId : checkItemIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("checkGroupId", checkGroupId);
                map.put("checkItemId", checkItemId);
                checkGroupMapper.setCheckGroupAndCheckItem(map);
            }
        }
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> checkGroups = checkGroupMapper.pageQuery(queryString);
        return new PageResult(checkGroups.getTotal(), checkGroups.getResult());
    }

    @Override
    public void deleteById(Integer id) {
        Long count = checkGroupMapper.findCountByCheckGroupId(id);
        if (count > 0) {
            //当前检查项被引用，不能删除
            throw new RuntimeException("当前检查组被引用，不能删除");
        }
        //删除关联表数据
        checkGroupMapper.deleteAssociation(id);
        //删除主表数据
        checkGroupMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkItemIds) {
        checkGroupMapper.updateByPrimaryKeySelective(checkGroup);
        //删除所有的现有关系
        checkGroupMapper.deleteAssociation(checkGroup.getId());
        //重新建立关系
        setCheckGroupAndCheckItem(checkGroup.getId(), checkItemIds);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        return checkGroupMapper.findCheckItemIdsByCheckGroupId(id);
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();
    }

}
